//
//  SHDiscountViewController.m
//  UI_CarHome
//
//  Created by dllo on 15/10/31.
//  Copyright (c) 2015年 沈浩. All rights reserved.
//

#import "SHDiscountViewController.h"
#import "SHHandle.h"
#import "SHDiscountModel.h"
#import "SHDiscountTableViewCell.h"
#import "SHDiscountCityModel.h"

#import "SHDetailViewController.h"
#import "SHObtainViewController.h"
#import "SHDiscountCityTableCell.h"
#define SEPARATORSTYLE [SHSingleton shareSingletion].isNight ? UITableViewCellSeparatorStyleNone : UITableViewCellSeparatorStyleSingleLine
@interface SHDiscountViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *discountArr;
@property(nonatomic, retain)NSMutableArray *cityArr;
@property(nonatomic, retain)UIButton *cityButton;
@property(nonatomic, retain)UITableView *cityTableView;
@property(nonatomic, retain)UIView *cityView;
@property(nonatomic, retain)NSArray *indexArr;

@property(nonatomic, retain)UILabel *noDiscountLabel;
@property(nonatomic, retain)NSString *webStr;

@property(nonatomic, assign)NSInteger index;

@end

@implementation SHDiscountViewController
- (void)dealloc
{
    [_webStr release];
    [_noDiscountLabel release];
    [_indexArr release];
    [_cityView release];
    [_cityTableView release];
    [_cityButton release];
    [_cityArr release];
    [_discountArr release];
    [_tableView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    http://mrobot.pcauto.com.cn/v3/price/promotionList?areaId=248&pageNo=1&orderBy=discountRange
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.cityView = [[UIView alloc] initWithFrame:CGRectMake(WIDTH, 0, 255, HEIGHT)];
    [self.view addSubview:self.cityView];
    [_cityView release];
    
    [self.cityView addSubview:self.cityTableView];
    [_cityTableView release];
    
    self.view.backgroundColor = BACKGROUNDCOLOR;
    self.tableView.backgroundColor = BACKGROUNDCOLOR;
    self.tableView.separatorStyle = SEPARATORSTYLE;
    self.cityView.backgroundColor = BACKGROUNDCOLOR;
    self.cityTableView.backgroundColor = BACKGROUNDCOLOR;
    self.cityTableView.separatorStyle = SEPARATORSTYLE;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isNight:) name:@"isNight" object:nil];
    
    [SHSingleton shareSingletion].areaId = @"248";//大连
    [self createData];
    self.cityButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.cityButton.frame = CGRectMake(0, 0, 120, 40);
    [self.cityButton setTitle:@"大连" forState:UIControlStateNormal];
    [self.cityButton setImage:[UIImage imageNamed:@"address"] forState:UIControlStateNormal];
    [self.cityButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    self.cityButton.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 10);
    self.cityButton.titleLabel.textAlignment = NSTextAlignmentRight;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.cityButton];
    [self.cityButton addTarget:self action:@selector(cityButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.indexArr = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"J",@"K",@"L",@"M",@"N",@"P",@"Q",@"R",@"S",@"T",@"W",@"X",@"Y",@"Z"];
    
    // 轻扫
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
    [self.cityView addGestureRecognizer:swipe];
    [swipe release];
    swipe.direction = UISwipeGestureRecognizerDirectionRight;
 
    
}
- (void)isNight:(NSNotification *)notification {
    [self.tableView reloadData];
    [self.cityTableView reloadData];
    self.cityView.backgroundColor = BACKGROUNDCOLOR;
    self.cityTableView.backgroundColor = BACKGROUNDCOLOR;
    self.tableView.backgroundColor = BACKGROUNDCOLOR;
    self.tableView.separatorStyle = SEPARATORSTYLE;
    self.cityTableView.separatorStyle = SEPARATORSTYLE;
}

#pragma mark --轻扫
- (void)swipeAction:(UISwipeGestureRecognizer *)swipe {
    [UIView animateWithDuration:1 animations:^{
        self.cityView.frame = CGRectMake(WIDTH, 0, 255, HEIGHT);
    }];

}
#pragma mark --city数据处理
- (void)cityButtonAction:(UIButton *)button {
    self.cityView.frame = CGRectMake(120, 0, WIDTH - 120, HEIGHT);
    [SHNetWorkingTool getNetWorking:@"http://mrobot.pcauto.com.cn/v2/cms/area_tree?order=alpha" block:^(id result) {
        self.cityArr = [NSMutableArray array];
        for (NSInteger i = 0; i < self.indexArr.count; i++) {
            NSMutableArray *tempArr = [SHDiscountCityModel baseModelByArr:result[self.indexArr[i]]];
          
            [self.cityArr addObject:tempArr];
        }
     
        [self.cityTableView reloadData];

    }];
}
#pragma mark --城市tableView
- (UITableView *)cityTableView {
    if (!_cityTableView) {
        self.cityTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 255, HEIGHT) style:UITableViewStylePlain];
        self.cityTableView.dataSource = self;
        self.cityTableView.delegate = self;
    }
    return _cityTableView;
}

#pragma mark --tableView
- (UITableView *)tableView {
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.tableView.rowHeight = 150;
    
    }
    return _tableView;
}
#pragma mark --createData
- (void)createData
{
    if (self.noDiscountLabel) {
        [self.noDiscountLabel removeFromSuperview];
    }
    NSString *urlStr = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/price/promotionList?areaId=%@&pageNo=0&orderBy=discountRange", [SHSingleton shareSingletion].areaId];
    [SHNetWorkingTool getNetWorking:urlStr block:^(id result) {
        NSDictionary *dic =result;
        self.discountArr = [NSMutableArray array];
        self.discountArr = [SHDiscountModel baseModelByArr:dic[@"data"]];
        
        if ([dic[@"data"] count] == 0) {
            self.noDiscountLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, - 64, WIDTH, HEIGHT)];
            self.noDiscountLabel.backgroundColor = [UIColor whiteColor];
            self.noDiscountLabel.text = @"抱歉: 当前条件下暂无降价信息";
            self.noDiscountLabel.textAlignment = NSTextAlignmentCenter;
            [self.tableView addSubview:self.noDiscountLabel];
            [_noDiscountLabel release];
        }
        [self.tableView reloadData];
    }];
}


#pragma mark -- tableView的协议方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        static NSString *reuse = @"discount";
        SHDiscountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[[SHDiscountTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
        }
        SHDiscountModel *model = self.discountArr[indexPath.row];
        [cell.specpicImageView sd_setImageWithURL:[NSURL URLWithString:model.image] placeholderImage:PLACEPICTURE];
        cell.specnameLabel.text = model.modelName;
        cell.specnameLabel.textColor = TEXTCOLOR;
        cell.dealerpriceLabel.text = [NSString stringWithFormat:@"%@%@", model.modelPrice, @"万"];
        cell.fctpriceLabel.text = [NSString stringWithFormat:@"%@%@", model.dealerPrice, @"万"];
        cell.addressLabel.text = model.area;
        cell.shortnameLabel.text = model.dealerName;
        [cell.phoneButton addTarget:self action:@selector(phoneButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.lowPriceButton addTarget:self action:@selector(lowPriceButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        self.index = indexPath.row;
        return cell;

    } else {
        static NSString *reuse = @"city";
        SHDiscountCityTableCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[[SHDiscountCityTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
        }
        SHDiscountCityModel *model = self.cityArr[indexPath.section][indexPath.row];
        cell.tittleLabel.textColor = TEXTCOLOR;
        cell.tittleLabel.text = model.city;
        return cell;
    }
    }

#pragma mark button点击方法
- (void)phoneButtonAction:(UIButton *)button {
    
    
}
- (void)lowPriceButtonAction:(UIButton *)button {
    SHObtainViewController *lowPrice = [[SHObtainViewController alloc] init];
    [self.navigationController pushViewController:lowPrice animated:YES];
    SHDiscountModel *model = self.discountArr[self.index];
    lowPrice.discountModel = model;
    [lowPrice release];
}
#pragma mark -- 每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return self.discountArr.count;
    } else {
        NSArray *arr = self.cityArr[section];
        return arr.count;
    }

}
#pragma mark --每个分区的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (tableView == self.cityTableView) {
        return self.indexArr[section];
    } else {
        return nil;
    }
}
#pragma mark -- 指定当前的分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.tableView) {
        return 1;
    } else {
        return self.cityArr.count;
    }
}

#pragma mark --索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (tableView == self.cityTableView) {
        return self.indexArr;
    } else {
        return nil;
    }
}

#pragma mark --cell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        SHDiscountModel *model = self.discountArr[indexPath.row];
       SHDetailViewController *detail = [[SHDetailViewController alloc] init];
        [self.navigationController pushViewController:detail animated:YES];
        self.webStr = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/price/promotionDetailv45/9982500?modelId=%@&type=0", model.modelId];
        detail.webStr = self.webStr;
        [detail release];
      } else {
        NSArray *arr = self.cityArr[indexPath.section];
        SHDiscountCityModel *cityModel = arr[indexPath.row];
        [SHSingleton shareSingletion].areaId = cityModel.areaId;
        [self.cityButton setTitle:cityModel.city forState:UIControlStateNormal];
        [UIView animateWithDuration:1 animations:^{
        self.cityView.frame = CGRectMake(WIDTH, 0, WIDTH - 120, HEIGHT);
        }];
        [self createData];
    }
   }


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
